package com.h3bpm.web.common.controller;

import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.service.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.web.common.H3Property;
import com.h3bpm.web.common.utils.SqlUtil;
import data.DataRow;
import data.DataTable;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author: cjj
 * @Date: 2020/7/10
 */
@RestController
@RequestMapping("/Portal/ProbabilityController")
public class ProbabilityController extends ControllerBase {
    private static Logger logger = LoggerFactory.getLogger(ProbabilityController.class);


    @Override
    public String getFunctionCode() {
        return null;
    }

    /**
     * 获取概率
     * @param workflowCode 流程实例名称
     * @return
     */
    @RequestMapping("/getProbabilityNumber")
    @ResponseBody
    public JSONObject getNumber(String workflowCode,@RequestParam(required = false) String randoms){
        logger.info("获取概率参数workflowCode:"+workflowCode+",random:"+randoms);
        AssertUtil.assertNotNull(workflowCode);
        String[] randomArr = new String[]{};
        if(StringUtils.isNotBlank(randoms)){
            randomArr = randoms.split(";");
        }else{
            randomArr = H3Property.DEFAULT_PROBABILITY_NO;
        }
        JSONObject result = new JSONObject();
        String sql="SELECT max(SUBSTRING(SequenceNo, -3)) as SequenceNo from ot_instancecontext where WorkflowCode= '%s'";
        String randomFlag = "0";
        try {
            DataTable table = SqlUtil.doQuery(String.format(sql, workflowCode));
            List<DataRow> entityRows = table.getEntityRows();
            if(!entityRows.isEmpty()&&entityRows.size()>0) {
                int number = entityRows.get(0).getInt("SequenceNo")+1;
                randomFlag = Arrays.asList(randomArr).contains(String.valueOf(number%100))?"1":"0";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.put("randomFlag",randomFlag);
        result.put("state", "200");
        result.put("msg", "success");
        return result;
    }
}
